package org.company.saturn.hadoop.yarn;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.WritableComparator;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Partitioner;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.jasper.tagplugins.jstl.core.Otherwise;
import org.company.saturn.hadoop.vo.IntPair;
import org.company.saturn.hadoop.yarn.map.SecondSortMapper;
import org.company.saturn.hadoop.yarn.reduce.SecondSrotReducer;

import com.sun.jersey.core.impl.provider.entity.XMLJAXBElementProvider.Text;

public class SecondSortMain extends Configured implements Tool{
	
	/**
	 * 自定义分区类
	 * @author hucw
	 *
	 */
	static class FirstPartition extends Partitioner<IntPair, IntWritable> {
		@Override
		public int getPartition(IntPair key, IntWritable value, int numPartitions) {
			return (key.getFirst() * 127) % numPartitions;
		}
	}
	
	/**
	 * 自定义分组类
	 * @author hucw
	 *
	 */
	static class FirstGroupingComparator extends WritableComparator {
		@Override
		public int compare(Object a, Object b) {
			IntPair ip1 = (IntPair) a;
			IntPair ip2 = (IntPair) b;
			int l = ip1.getFirst();
			int r = ip2.getFirst();
			return l == r ? 0 : (l < r ? -1 : 1);
		}
	}

	@Override
	public int run(String[] args) throws Exception {
		Configuration conf = this.getConf();
		Job job = Job.getInstance(conf, "mysecondsort");
		
		job.setJarByClass(SecondSortMain.class);
		job.setMapperClass(SecondSortMapper.class);
		job.setReducerClass(SecondSrotReducer.class);
		job.setPartitionerClass(FirstPartition.class);
		job.setGroupingComparatorClass(FirstGroupingComparator.class);
		
		job.setMapOutputKeyClass(IntPair.class);
		job.setMapOutputValueClass(IntWritable.class);
		job.setOutputKeyClass(IntWritable.class);
		job.setOutputValueClass(Text.class);
		
		job.setInputFormatClass(TextInputFormat.class);
		job.setOutputFormatClass(TextOutputFormat.class);
		
		FileInputFormat.addInputPath(job, new Path(args[0]));
		FileOutputFormat.setOutputPath(job, new Path(args[1]));
		return job.waitForCompletion(true) ? 0 : 1;
	}

	public static void main(String[] args) throws Exception {
		int exitCode = ToolRunner.run(new SecondSortMain(), args);
		System.out.println(exitCode);
	}
}
